<template>
	<el-dialog
		title="取消订单提示信息"
		v-model="dialogVisible"
		:destroy-on-close="true"
		width="500px"
		class="cancel-order-dialog"
	>
		<div class="cancel-form">
			<el-form ref="formRef" :model="formData" :rules="rules">
				<el-form-item prop="reason" class="mb-4">
					<el-input
						v-model="formData.reason"
						type="textarea"
						:rows="4"
						placeholder="请输入原因说明"
					/>
				</el-form-item>
			</el-form>

			<!-- 提示信息 -->
			<div class="tip-info">
				<p class="text-red-500">注：订单取消后将不能进行后续运输作业。</p>
			</div>
		</div>

		<template #footer>
			<el-button @click="handleCancel">取消</el-button>
			<el-button type="primary" @click="handleConfirm" :loading="submitting">
				确定
			</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	orderData: {
		type: Object,
		default: () => ({}),
	},
});

const emit = defineEmits(['update:modelValue', 'success']);

const dialogVisible = ref(false);
const submitting = ref(false);
const formRef = ref(null);

// 表单数据
const formData = reactive({
	reason: '',
});

// 表单校验规则
const rules = {
	reason: [
		{ required: true, message: '请输入取消原因', trigger: 'blur' },
		{ min: 5, max: 200, message: '原因说明长度为5-200个字符', trigger: 'blur' },
	],
};

// 监听弹窗显示状态
watch(
	() => props.modelValue,
	(val) => {
		dialogVisible.value = val;
		if (val) {
			formData.reason = '';
		}
	},
);

// 监听弹窗关闭
watch(dialogVisible, (val) => {
	emit('update:modelValue', val);
});

// 取消
const handleCancel = () => {
	dialogVisible.value = false;
};

// 确认取消订单
const handleConfirm = async () => {
	if (!formRef.value) return;

	await formRef.value.validate(async (valid, fields) => {
		if (valid) {
			submitting.value = true;
			try {
				// TODO: 调用取消订单接口
				console.log('取消订单：', {
					orderNo: props.orderData.orderNo,
					reason: formData.reason,
				});
				ElMessage.success('订单已取消');
				dialogVisible.value = false;
				emit('success');
			} finally {
				submitting.value = false;
			}
		} else {
			console.log('校验失败', fields);
		}
	});
};
</script>

<style lang="scss" scoped>
.cancel-order-dialog {
	:deep(.el-dialog__body) {
		padding: 20px 24px;
	}

	.tip-info {
		font-size: 14px;
	}
}
</style>
